package anti5mao;

import java.io.IOException;

import javax.servlet.http.*;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;

@SuppressWarnings("serial")
public class Anti5maoServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
			Twitter twitter = getClient();
			try {
	            StringBuffer callbackURL = req.getRequestURL();
	            int index = callbackURL.lastIndexOf("/");
	            callbackURL.replace(index, callbackURL.length(), "").append("/callback");

	            RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
	            resp.addCookie(new Cookie("req_t", requestToken.getToken()));
	            resp.addCookie(new Cookie("req_t_s", requestToken.getTokenSecret()));
	            resp.sendRedirect(requestToken.getAuthenticationURL());

	        } catch (TwitterException e) {
	        	e.printStackTrace();
	        	resp.getWriter().println("error!");
	        }
	}
	
	
	
	public static Twitter getClient(){
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true)
		  .setOAuthConsumerKey("SSkzZ0Yzwmzc9ZuWCETpjg")
		  .setOAuthConsumerSecret("QIXkmtOUKEgtJAeZ5Pnb2UuZ4g60ZsWXcJvutyALM");
		Twitter twitter = new TwitterFactory(cb.build()).getInstance();
		return twitter;
	}
}
